package pwr.zpi.twop;

import java.util.List;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.GLCommon;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;

public class RendererGL20 implements Renderer {
	private final Color boundingBoxColor = Color.valueOf("002EB8");
	private final int boxSize = ModelProvider.BOX_SIZE;
	private final float scale = ModelProvider.SCALE;
	
	private PerspectiveCamera camera;
	
	private CameraInputController cameraController;
	
    private ModelBatch modelBatch;
    private ShapeRenderer shapeRenderer;
    private KeyboardInputHandler inputHandler;
	private List<DrawablePoint> pointList;

	public void init(ModelProvider modelProvider) {
		camera = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
		camera.position.set(8.441416f, 7.953529f, 10.415563f);
		camera.direction.set(-0.93793523f, -0.8837246f, -1.157285f);
		camera.near = 0.1f;
		camera.far = 300f;
		
		camera.update();
		
		shapeRenderer = new ShapeRenderer();
		cameraController = new CameraInputController(camera);
		Gdx.input.setInputProcessor(cameraController);
		modelBatch = new ModelBatch();
		
		pointList = modelProvider.getPoints();
	}

	@Override
	public void render(float delta) {
		float halfBoxSize = boxSize / 2;
		
		cameraController.update();
		
		GLCommon gl = Gdx.gl;
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
		
		camera.update();
		
		modelBatch.begin(camera);
		shapeRenderer.setProjectionMatrix(camera.combined);
		
		shapeRenderer.begin(ShapeType.Line);
		shapeRenderer.setColor(boundingBoxColor );
		shapeRenderer.box(-(halfBoxSize*scale), -(halfBoxSize*scale), (halfBoxSize*scale), 
				(boxSize*scale), (boxSize*scale), (boxSize*scale));
		shapeRenderer.end();
		
		shapeRenderer.begin(ShapeType.Point);
		
		List<DrawablePoint> points = pointList;
		for (DrawablePoint dp : points) {
			dp.draw(shapeRenderer);
		}
		
		shapeRenderer.end();
		modelBatch.end();
		
		inputHandler.update(Gdx.input);
	}
	
	public void setPointList(List<DrawablePoint> pointList) {
		this.pointList = pointList;
	}
	
	public void setInputHandler(KeyboardInputHandler inputHandler) {
		this.inputHandler = inputHandler;
	}
}
